//
//  EJSSearchHistoryRequest.m
//  EnjoyShoppingStreet
//
//  Created by lifayu on 2017/12/21.
//  Copyright © 2017年 lifayu. All rights reserved.
//

#import "EJSSearchHistoryRequest.h"

#define EJSSearchHistory   @"EJSSearchHistory"

@implementation EJSSearchHistoryRequest

- (NSString *)uri{
    return @"/api/user_keyword/list";
}

- (Class)responseDataClass{
    return [EJSSearchHistoryModel class];
}


+ (NSArray *)getSearchHistory{
    NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
    NSArray *array = [userDefaults arrayForKey:EJSSearchHistory];
    [userDefaults synchronize];
    
    NSMutableArray *history = [NSMutableArray array];
    for (NSString *string in array) {
        EJSSearchHistoryModel *model = [EJSSearchHistoryModel new];
        model.content = string;
        [history addObject:model];
    }
    
    return history;
}

+ (void)setSearchHistory:(NSString *)keyword{
    if(!keyword){
        return;
    }
    NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
    NSMutableArray *history = [[userDefaults arrayForKey:EJSSearchHistory] mutableCopy];

    if(history){

        if(history.count >= 10){
            [history removeObjectAtIndex:0];
        }
        if ([history containsObject:keyword]) {
            [history removeObject:keyword];
            [history insertObject:keyword atIndex:0];
        }else {
            [history insertObject:keyword atIndex:0];
        }
    }else{
            history = [NSMutableArray array];
            [history addObject:keyword];
    }

    [userDefaults setObject:history forKey:EJSSearchHistory];
    [userDefaults synchronize];
}

+ (void)cleanSearchHistory{
    NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
    [userDefaults setObject:nil forKey:EJSSearchHistory];
    [userDefaults synchronize];
}

@end
